package com.automobile.backstage.controller;


import com.automobile.backstage.domain.User;
import com.automobile.backstage.service.UserService;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.ibatis.annotations.Select;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping(path = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    public static final String CHECK_CODE_KEY = "CHECK_CODE_KEY";


    /*
     * 注册
     */
    @RequestMapping(path = "/register", produces = "application/json; charset=utf-8")
    public @ResponseBody Map<String, Object> register(@RequestBody User user) {
        System.out.println(user);
        Map<String, Object> msgMap = new HashMap<String, Object>();

        user.setPassword(new SimpleHash("MD5", user.getPassword(), ByteSource.Util.bytes(user.getPhone()), 1024).toString());
        boolean result = false;
        if(user.getId()==0){
            result = userService.save(user);
            System.out.println(2);
        }else{
            result = userService.updateUser(user);
            System.out.println(3);

        }
        if(!result) {
            msgMap.put("msg", "手机号或邮箱已注册过，如忘记密码请前往修改密码。");
            msgMap.put("result",0);
        }else {
            msgMap.put("result", 1);
        }

        return msgMap;
    }



    @RequestMapping("/findAll")
    public @ResponseBody PageInfo findAll(@RequestParam(value = "page",required = true ,defaultValue = "1")Integer page,
                                            @RequestParam(value = "limit",required = true,defaultValue = "10")Integer size) throws Exception {
        List<User> users = userService.findAll(page ,size);
        PageInfo pageInfo = new PageInfo(users);

        return pageInfo;
    }

    @RequestMapping("/findAllMerchant")
    public @ResponseBody PageInfo findAllMerchant(@RequestParam(value = "page",required = true ,defaultValue = "1")Integer page,
                                          @RequestParam(value = "limit",required = true,defaultValue = "10")Integer size) throws Exception {
        List<User> users = userService.findAllMerchant(page ,size);
        PageInfo pageInfo = new PageInfo(users);

        return pageInfo;
    }

    @RequestMapping("/findUserById")
    public @ResponseBody List<User> findUserById(@RequestParam(value = "page",required = true ,defaultValue = "1")Integer page,
                                           @RequestParam(value = "limit",required = true,defaultValue = "10")Integer size,
                                           @RequestParam(value = "UserId")Integer id){
        User user = userService.findUserById(id);
        List<User> users = new ArrayList<>();
        users.add(user);
        return users;
    }

    @RequestMapping(value = "/del",method = RequestMethod.POST)
    public @ResponseBody int del(@RequestBody List<Integer> jsonDelId){
        userService.del(jsonDelId);
        return 1;
    }


    @RequestMapping(value = "/lock")
    public @ResponseBody int lock(@RequestBody String json){
        JsonParser jp = new JsonParser();
        JsonObject jo = jp.parse(json).getAsJsonObject();
        int id = Integer.parseInt(jo.get("id").toString());
        String status = jo.get("flag").toString().equals("true")?"Y":"N";
        userService.updateLock(status,id);
        return 1;
    }

    @RequestMapping("/login")
    public @ResponseBody Map<String,Object> login(@RequestBody User user){
        System.out.println(user);
        Map<String, Object> msgMap = new HashMap<String, Object>();

        Subject currentUser = SecurityUtils.getSubject();
        if(!currentUser.isAuthenticated()){
            UsernamePasswordToken token = new UsernamePasswordToken(user.getName(),user.getPassword());

            try {
                currentUser.login(token);
            } catch (AuthenticationException e) {
                msgMap.put("msg",e.getMessage());
                msgMap.put("result",0);
                return msgMap;
            }

        }

        msgMap.put("result",1);
        return msgMap;
    }

    @RequestMapping("/message")
    public @ResponseBody User message(){
        User user = null;
        Object obj = SecurityUtils.getSubject().getPrincipal();
        if(obj!=null&&obj instanceof User){
            user = (User) obj;
        }
        return user;
    }

}
